'use client'

import { useState, useEffect } from 'react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Calendar } from '@/components/ui/calendar'
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
import { 
  CalendarIcon, 
  MapPinIcon, 
  PhoneIcon, 
  ClockIcon, 
  UserIcon, 
  CreditCardIcon, 
  CheckCircleIcon,
  XCircleIcon,
  SearchIcon,
  FilterIcon,
  PlusIcon,
  EditIcon,
  TrashIcon
} from 'lucide-react'
import { format } from 'date-fns'
import { zhCN } from 'date-fns/locale'
import { api, type Hospital, type Department, type Doctor, type TimeSlot, type CreateAppointmentRequest, type PatientInfo, type AppointmentOrder } from '@/lib/api'
import { toast } from 'sonner'

interface AppointmentStats {
  total: number
  pending: number
  confirmed: number
  completed: number
  cancelled: number
  todayAppointments: number
  upcomingAppointments: number
}

export default function AppointmentManagementPage() {
  const [activeTab, setActiveTab] = useState('overview')
  const [loading, setLoading] = useState(false)
  const [appointments, setAppointments] = useState<AppointmentOrder[]>([])
  const [hospitals, setHospitals] = useState<Hospital[]>([])
  const [departments, setDepartments] = useState<Department[]>([])
  const [doctors, setDoctors] = useState<Doctor[]>([])
  const [stats, setStats] = useState<AppointmentStats>({
    total: 0,
    pending: 0,
    confirmed: 0,
    completed: 0,
    cancelled: 0,
    todayAppointments: 0,
    upcomingAppointments: 0
  })
  
  // 筛选状态
  const [filter, setFilter] = useState({
    status: 'all',
    hospital: 'all',
    department: 'all',
    dateRange: 'all',
    search: ''
  })

  // 新预约表单状态
  const [showNewAppointmentDialog, setShowNewAppointmentDialog] = useState(false)
  const [newAppointment, setNewAppointment] = useState({
    hospitalId: '',
    departmentId: '',
    doctorId: '',
    appointmentDate: '',
    timeSlot: '',
    patientName: '',
    patientPhone: '',
    patientIdCard: ''
  })

  // 状态更新对话框
  const [showStatusDialog, setShowStatusDialog] = useState(false)
  const [statusUpdate, setStatusUpdate] = useState({
    appointmentId: '',
    appointmentInfo: '',
    newStatus: '',
    remark: ''
  })

  // 加载数据
  useEffect(() => {
    loadData()
  }, [])

  // 监听筛选条件变化
  useEffect(() => {
    loadAppointments()
  }, [filter.status, filter.hospital, filter.search])

  const loadData = async () => {
    try {
      setLoading(true)
      await Promise.all([
        loadAppointments(),
        loadHospitals(),
        loadStats()
      ])
    } catch (error) {
      console.error('加载数据失败:', error)
      toast.error('加载数据失败')
    } finally {
      setLoading(false)
    }
  }

  const loadAppointments = async () => {
    try {
      const response = await api.appointment.getAllAppointments({ 
        status: filter.status === 'all' ? undefined : filter.status,
        hospitalId: filter.hospital === 'all' ? undefined : filter.hospital,
        search: filter.search || undefined,
        page: 1,
        limit: 100
      })
      if (response.success) {
        setAppointments(response.data.appointments)
        loadStats() // 加载数据后重新计算统计
      }
    } catch (error) {
      console.error('加载预约列表失败:', error)
    }
  }

  const loadHospitals = async () => {
    try {
      const response = await api.appointment.getHospitals({ page: 1, limit: 50 })
      if (response.success) {
        setHospitals(response.data.hospitals)
      }
    } catch (error) {
      console.error('加载医院列表失败:', error)
    }
  }

  const loadStats = async () => {
    try {
      const response = await api.appointment.getAppointmentStats({
        hospitalId: filter.hospital === 'all' ? undefined : filter.hospital
      })
      if (response.success) {
        setStats(response.data.overview)
      }
    } catch (error) {
      console.error('加载统计数据失败:', error)
      // 降级到本地计算
      const total = appointments.length
      const pending = appointments.filter(apt => apt.status === 'pending').length
      const confirmed = appointments.filter(apt => apt.status === 'confirmed').length
      const completed = appointments.filter(apt => apt.status === 'completed').length
      const cancelled = appointments.filter(apt => apt.status === 'cancelled').length
      
      const today = new Date().toISOString().split('T')[0]
      const todayAppointments = appointments.filter(apt => apt.appointmentDate === today).length
      const upcomingAppointments = appointments.filter(apt => 
        new Date(apt.appointmentDate) > new Date() && apt.status !== 'cancelled'
      ).length

      setStats({
        total,
        pending,
        confirmed,
        completed,
        cancelled,
        todayAppointments,
        upcomingAppointments
      })
    }
  }

  // 打开状态更新对话框
  const openStatusDialog = (appointment: AppointmentOrder, newStatus: string) => {
    setStatusUpdate({
      appointmentId: appointment.id,
      appointmentInfo: `${appointment.patientInfo?.name || '患者'} - ${appointment.doctorName} - ${appointment.timeSlot}`,
      newStatus,
      remark: appointment.remark || ''
    })
    setShowStatusDialog(true)
  }

  // 更新预约状态
  const updateAppointmentStatus = async (appointmentId: string, newStatus: string, remark?: string) => {
    try {
      const response = await api.appointment.updateAppointmentStatus(appointmentId, { 
        status: newStatus, 
        remark 
      })
      if (response.success) {
        setAppointments(prev => prev.map(apt => 
          apt.id === appointmentId ? { ...apt, status: newStatus as any, remark } : apt
        ))
        toast.success('预约状态更新成功')
        loadStats() // 重新加载统计数据
      } else {
        toast.error(response.message || '更新失败')
      }
    } catch (error) {
      console.error('更新预约状态失败:', error)
      toast.error('更新预约状态失败')
    }
  }

  // 确认状态更新
  const confirmStatusUpdate = async () => {
    await updateAppointmentStatus(statusUpdate.appointmentId, statusUpdate.newStatus, statusUpdate.remark)
    setShowStatusDialog(false)
    setStatusUpdate({ appointmentId: '', appointmentInfo: '', newStatus: '', remark: '' })
  }

  // 取消预约
  const cancelAppointment = async (appointmentId: string) => {
    try {
      const response = await api.appointment.cancelAppointment(appointmentId)
      if (response.success) {
        setAppointments(prev => prev.map(apt => 
          apt.id === appointmentId ? { ...apt, status: 'cancelled' } : apt
        ))
        toast.success('预约已取消')
      }
    } catch (error) {
      console.error('取消预约失败:', error)
      toast.error('取消预约失败')
    }
  }

  // 过滤预约列表
  const filteredAppointments = appointments.filter(appointment => {
    if (filter.status !== 'all' && appointment.status !== filter.status) return false
    if (filter.hospital !== 'all' && appointment.hospitalId !== filter.hospital) return false
    if (filter.search && !appointment.patientInfo?.name?.toLowerCase().includes(filter.search.toLowerCase()) && 
        !appointment.doctorName.toLowerCase().includes(filter.search.toLowerCase())) return false
    return true
  })

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'pending': return 'bg-yellow-100 text-yellow-800'
      case 'confirmed': return 'bg-blue-100 text-blue-800'
      case 'completed': return 'bg-green-100 text-green-800'
      case 'cancelled': return 'bg-red-100 text-red-800'
      default: return 'bg-gray-100 text-gray-800'
    }
  }

  const getStatusText = (status: string) => {
    switch (status) {
      case 'pending': return '待确认'
      case 'confirmed': return '已确认'
      case 'completed': return '已完成'
      case 'cancelled': return '已取消'
      default: return '未知'
    }
  }

  return (
    <div className="container mx-auto px-4 py-8">
      <div className="mb-8">
        <h1 className="text-3xl font-bold text-gray-900 mb-2">预约管理中心</h1>
        <p className="text-gray-600">管理和监控所有预约挂号信息</p>
      </div>

      <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
        <TabsList className="grid w-full grid-cols-4">
          <TabsTrigger value="overview">概览统计</TabsTrigger>
          <TabsTrigger value="appointments">预约列表</TabsTrigger>
          <TabsTrigger value="schedule">排班管理</TabsTrigger>
          <TabsTrigger value="settings">系统设置</TabsTrigger>
        </TabsList>

        {/* 概览统计 */}
        <TabsContent value="overview" className="space-y-6">
          {/* 统计卡片 */}
          <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-4">
            <Card>
              <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                <CardTitle className="text-sm font-medium">总预约数</CardTitle>
                <CalendarIcon className="h-4 w-4 text-muted-foreground" />
              </CardHeader>
              <CardContent>
                <div className="text-2xl font-bold">{stats.total}</div>
                <p className="text-xs text-muted-foreground">
                  今日新增 {stats.todayAppointments} 个
                </p>
              </CardContent>
            </Card>

            <Card>
              <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                <CardTitle className="text-sm font-medium">待确认</CardTitle>
                <ClockIcon className="h-4 w-4 text-muted-foreground" />
              </CardHeader>
              <CardContent>
                <div className="text-2xl font-bold text-yellow-600">{stats.pending}</div>
                <p className="text-xs text-muted-foreground">
                  需要及时处理
                </p>
              </CardContent>
            </Card>

            <Card>
              <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                <CardTitle className="text-sm font-medium">已确认</CardTitle>
                <CheckCircleIcon className="h-4 w-4 text-muted-foreground" />
              </CardHeader>
              <CardContent>
                <div className="text-2xl font-bold text-blue-600">{stats.confirmed}</div>
                <p className="text-xs text-muted-foreground">
                  即将就诊 {stats.upcomingAppointments} 个
                </p>
              </CardContent>
            </Card>

            <Card>
              <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                <CardTitle className="text-sm font-medium">已完成</CardTitle>
                <CheckCircleIcon className="h-4 w-4 text-muted-foreground" />
              </CardHeader>
              <CardContent>
                <div className="text-2xl font-bold text-green-600">{stats.completed}</div>
                <p className="text-xs text-muted-foreground">
                  完成率 {stats.total > 0 ? Math.round((stats.completed / stats.total) * 100) : 0}%
                </p>
              </CardContent>
            </Card>
          </div>

          {/* 今日预约概览 */}
          <Card>
            <CardHeader>
              <CardTitle>今日预约概览</CardTitle>
              <CardDescription>今天的预约情况统计</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="space-y-4">
                {appointments
                  .filter(apt => apt.appointmentDate === new Date().toISOString().split('T')[0])
                  .slice(0, 5)
                  .map((appointment) => (
                    <div key={appointment.id} className="flex items-center justify-between border-b pb-4">
                      <div>
                        <p className="font-medium">{appointment.patientInfo?.name || '患者'}</p>
                        <p className="text-sm text-gray-600">
                          {appointment.doctorName} · {appointment.timeSlot}
                        </p>
                      </div>
                      <Badge className={getStatusColor(appointment.status)}>
                        {getStatusText(appointment.status)}
                      </Badge>
                    </div>
                  ))}
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        {/* 预约列表 */}
        <TabsContent value="appointments" className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center justify-between">
                预约列表
                <Button onClick={() => setShowNewAppointmentDialog(true)}>
                  <PlusIcon className="w-4 h-4 mr-2" />
                  新建预约
                </Button>
              </CardTitle>
              <CardDescription>查看和管理所有预约信息</CardDescription>
            </CardHeader>
            <CardContent>
              {/* 筛选器 */}
              <div className="flex flex-wrap gap-4 mb-6">
                <div className="flex-1 min-w-60">
                  <Input
                    placeholder="搜索患者姓名或医生姓名..."
                    value={filter.search}
                    onChange={(e) => setFilter(prev => ({ ...prev, search: e.target.value }))}
                    className="w-full"
                  />
                </div>
                <Select value={filter.status} onValueChange={(value) => setFilter(prev => ({ ...prev, status: value }))}>
                  <SelectTrigger className="w-32">
                    <SelectValue placeholder="状态" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">全部状态</SelectItem>
                    <SelectItem value="pending">待确认</SelectItem>
                    <SelectItem value="confirmed">已确认</SelectItem>
                    <SelectItem value="completed">已完成</SelectItem>
                    <SelectItem value="cancelled">已取消</SelectItem>
                  </SelectContent>
                </Select>
                <Select value={filter.hospital} onValueChange={(value) => setFilter(prev => ({ ...prev, hospital: value }))}>
                  <SelectTrigger className="w-40">
                    <SelectValue placeholder="医院" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">全部医院</SelectItem>
                    {hospitals.map(hospital => (
                      <SelectItem key={hospital.id} value={hospital.id}>
                        {hospital.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              {/* 预约表格 */}
              <div className="rounded-md border">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>患者信息</TableHead>
                      <TableHead>医院科室</TableHead>
                      <TableHead>医生</TableHead>
                      <TableHead>预约时间</TableHead>
                      <TableHead>状态</TableHead>
                      <TableHead>费用</TableHead>
                      <TableHead>备注</TableHead>
                      <TableHead>操作</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {filteredAppointments.map((appointment) => (
                      <TableRow key={appointment.id}>
                        <TableCell>
                          <div>
                            <p className="font-medium">{appointment.patientInfo?.name || '患者'}</p>
                            <p className="text-sm text-gray-600">{appointment.patientInfo?.phone}</p>
                          </div>
                        </TableCell>
                        <TableCell>
                          <div>
                            <p className="font-medium">{appointment.hospitalName}</p>
                            <p className="text-sm text-gray-600">{appointment.departmentName}</p>
                          </div>
                        </TableCell>
                        <TableCell>{appointment.doctorName}</TableCell>
                        <TableCell>
                          <div>
                            <p className="font-medium">{appointment.appointmentDate}</p>
                            <p className="text-sm text-gray-600">{appointment.timeSlot}</p>
                          </div>
                        </TableCell>
                        <TableCell>
                          <Badge className={getStatusColor(appointment.status)}>
                            {getStatusText(appointment.status)}
                          </Badge>
                        </TableCell>
                        <TableCell>¥{appointment.price}</TableCell>
                        <TableCell>
                          <div className="max-w-32">
                            {appointment.remark ? (
                              <span className="text-sm text-gray-600 truncate" title={appointment.remark}>
                                {appointment.remark}
                              </span>
                            ) : (
                              <span className="text-gray-400">-</span>
                            )}
                          </div>
                        </TableCell>
                        <TableCell>
                          <div className="flex space-x-2">
                            {appointment.status === 'pending' && (
                              <Button 
                                size="sm" 
                                onClick={() => openStatusDialog(appointment, 'confirmed')}
                              >
                                确认
                              </Button>
                            )}
                            {appointment.status === 'confirmed' && (
                              <Button 
                                size="sm" 
                                variant="outline"
                                onClick={() => openStatusDialog(appointment, 'completed')}
                              >
                                完成
                              </Button>
                            )}
                            {appointment.status !== 'cancelled' && appointment.status !== 'completed' && (
                              <Button 
                                size="sm" 
                                variant="destructive"
                                onClick={() => cancelAppointment(appointment.id)}
                              >
                                取消
                              </Button>
                            )}
                          </div>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        {/* 排班管理 */}
        <TabsContent value="schedule" className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle>医生排班管理</CardTitle>
              <CardDescription>管理医生的出诊时间和预约时段</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="text-center py-12 text-gray-500">
                <CalendarIcon className="w-16 h-16 mx-auto mb-4 text-gray-300" />
                <p>排班管理功能开发中...</p>
                <p className="text-sm">将包含医生排班、时段设置、请假管理等功能</p>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        {/* 系统设置 */}
        <TabsContent value="settings" className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle>预约系统设置</CardTitle>
              <CardDescription>配置预约规则和系统参数</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="space-y-6">
                <div>
                  <Label className="text-base font-medium">预约设置</Label>
                  <div className="grid gap-4 mt-4">
                    <div className="flex items-center justify-between">
                      <div>
                        <p className="font-medium">允许提前预约天数</p>
                        <p className="text-sm text-gray-600">患者可以提前多少天进行预约</p>
                      </div>
                      <Select defaultValue="30">
                        <SelectTrigger className="w-20">
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="7">7天</SelectItem>
                          <SelectItem value="15">15天</SelectItem>
                          <SelectItem value="30">30天</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>
                    
                    <div className="flex items-center justify-between">
                      <div>
                        <p className="font-medium">取消预约期限</p>
                        <p className="text-sm text-gray-600">就诊前多长时间不能取消预约</p>
                      </div>
                      <Select defaultValue="2">
                        <SelectTrigger className="w-20">
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="1">1小时</SelectItem>
                          <SelectItem value="2">2小时</SelectItem>
                          <SelectItem value="24">24小时</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>
                  </div>
                </div>

                <div>
                  <Label className="text-base font-medium">通知设置</Label>
                  <div className="grid gap-4 mt-4">
                    <div className="flex items-center justify-between">
                      <div>
                        <p className="font-medium">短信提醒</p>
                        <p className="text-sm text-gray-600">是否发送短信提醒</p>
                      </div>
                      <Button variant="outline" size="sm">开启</Button>
                    </div>
                    
                    <div className="flex items-center justify-between">
                      <div>
                        <p className="font-medium">邮件通知</p>
                        <p className="text-sm text-gray-600">是否发送邮件通知</p>
                      </div>
                      <Button variant="outline" size="sm">开启</Button>
                    </div>
                  </div>
                </div>
              </div>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>

      {/* 新建预约对话框 */}
      <Dialog open={showNewAppointmentDialog} onOpenChange={setShowNewAppointmentDialog}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>新建预约</DialogTitle>
            <DialogDescription>为患者创建新的预约记录</DialogDescription>
          </DialogHeader>
          <div className="grid gap-4 py-4">
            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label htmlFor="patient-name">患者姓名</Label>
                <Input
                  id="patient-name"
                  value={newAppointment.patientName}
                  onChange={(e) => setNewAppointment(prev => ({ ...prev, patientName: e.target.value }))}
                  placeholder="请输入患者姓名"
                />
              </div>
              <div>
                <Label htmlFor="patient-phone">联系电话</Label>
                <Input
                  id="patient-phone"
                  value={newAppointment.patientPhone}
                  onChange={(e) => setNewAppointment(prev => ({ ...prev, patientPhone: e.target.value }))}
                  placeholder="请输入联系电话"
                />
              </div>
            </div>
            
            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label>选择医院</Label>
                <Select value={newAppointment.hospitalId} onValueChange={(value) => setNewAppointment(prev => ({ ...prev, hospitalId: value }))}>
                  <SelectTrigger>
                    <SelectValue placeholder="请选择医院" />
                  </SelectTrigger>
                  <SelectContent>
                    {hospitals.map(hospital => (
                      <SelectItem key={hospital.id} value={hospital.id}>
                        {hospital.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div>
                <Label>预约日期</Label>
                <Input
                  type="date"
                  value={newAppointment.appointmentDate}
                  onChange={(e) => setNewAppointment(prev => ({ ...prev, appointmentDate: e.target.value }))}
                  min={new Date().toISOString().split('T')[0]}
                />
              </div>
            </div>
            
            <div>
              <Label htmlFor="patient-id">身份证号（可选）</Label>
              <Input
                id="patient-id"
                value={newAppointment.patientIdCard}
                onChange={(e) => setNewAppointment(prev => ({ ...prev, patientIdCard: e.target.value }))}
                placeholder="请输入身份证号"
              />
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowNewAppointmentDialog(false)}>
              取消
            </Button>
            <Button onClick={() => {
              // 这里处理创建预约的逻辑
              toast.success('预约创建成功')
              setShowNewAppointmentDialog(false)
            }}>
              创建预约
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 状态更新对话框 */}
      <Dialog open={showStatusDialog} onOpenChange={setShowStatusDialog}>
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle>更新预约状态</DialogTitle>
            <DialogDescription>
              为预约 {statusUpdate.appointmentInfo} 更新状态
            </DialogDescription>
          </DialogHeader>
          <div className="grid gap-4 py-4">
            <div>
              <Label htmlFor="new-status">新状态</Label>
              <Select value={statusUpdate.newStatus} onValueChange={(value) => setStatusUpdate(prev => ({ ...prev, newStatus: value }))}>
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="pending">待确认</SelectItem>
                  <SelectItem value="confirmed">已确认</SelectItem>
                  <SelectItem value="completed">已完成</SelectItem>
                  <SelectItem value="cancelled">已取消</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div>
              <Label htmlFor="remark">备注（可选）</Label>
              <Input
                id="remark"
                value={statusUpdate.remark}
                onChange={(e) => setStatusUpdate(prev => ({ ...prev, remark: e.target.value }))}
                placeholder="添加管理员备注..."
              />
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowStatusDialog(false)}>
              取消
            </Button>
            <Button onClick={confirmStatusUpdate}>
              确认更新
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}